package com.codeos.khttp;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class KUrl {


    private String mProtocal;
    private String mHost;
    private int mPort = 80;
    private String mTotalFilePath = "";
    private String mFilePath = "";
    private String mParamString = "";
    private String mHostIP = null;
    private Map<String, String> mParamMap = new HashMap<String, String>();

    public KUrl(String url) {

        // 如果不带协议，默认为http
        if(url.contains("://") == false) {
            url = "http://"+url;
        }
//        System.out.println("url: "+url);

        // 如果只有host地址则追加斜杠
        if(url.matches("[\\S]*?://[\\S]*?/[\\S]*") == false) {
            url += "/";
        }
//        System.out.println("url: "+url);

        Pattern pattern = Pattern.compile("([\\S]*?)://([\\S]*?)(/[\\S]*)");
        Matcher matcher = pattern.matcher(url);
        if(matcher.matches() == false) {
            throw new IllegalArgumentException("not support url format!");
        } else {
//            System.out.println("match");
//            System.out.println("protocol: "+matcher.group(1));
//            System.out.println("host: "+matcher.group(2));
//            System.out.println("file: "+matcher.group(3));

            mProtocal = matcher.group(1);
            mHost = matcher.group(2);
            mTotalFilePath = matcher.group(3);

            // 解析port
            String[] hostArray = mHost.split(":");
            if(hostArray.length == 1) {
                mPort = 80;
//                System.out.println("port: "+mPort);
            } else if(hostArray.length == 2) {
                mHost = hostArray[0];
                mPort = Integer.parseInt(hostArray[1]);
//                System.out.println("mHost: "+mHost);
//                System.out.println("port: "+mPort);
            } else {
                throw new IllegalArgumentException("illegal url host session: "+mHost);
            }

            // 解析totalPath
            if(mTotalFilePath.contains("?")) {
                Pattern subPattern = Pattern.compile("(/[\\S]*?)\\?([\\S]*)");
                Matcher subMatcher = subPattern.matcher(mTotalFilePath);
                if (subMatcher.matches() == false) {
                    throw new IllegalArgumentException("parse params fail!");
                } else {
//                    System.out.println("filePath: "+subMatcher.group(1));
//                    System.out.println("params: "+subMatcher.group(2));
                    mFilePath = subMatcher.group(1);
                    mParamString = subMatcher.group(2);

                    try {
                        // URL参数解析到map结构
                        String[] params = mParamString.split("&");
                        for (int i = 0; i < params.length; i++) {
                            String[] subParam = params[i].split("=");
                            if(subParam.length <= 1) {
                                mParamMap.put(subParam[0], "");
//                                System.out.println("key: " + subParam[0] + ", value: ");
                            } else {
                                mParamMap.put(subParam[0], subParam[1]);
//                                System.out.println("key: " + subParam[0] + ", value: " + subParam[1]);
                            }
                        }
                    } catch (Exception e) {
                        throw new IllegalArgumentException("illegal url param: "+mParamString);
                    }
                }
            }
        }
    }

    public String getProtocal() {
        return mProtocal;
    }

    public String getHost() {
        return mHost;
    }

    public String getFilePath() {
        return mFilePath;
    }

    public String getTotalFilePath() {
        return mTotalFilePath;
    }

    public Map<String, String> getUrlParams() {
        return mParamMap;
    }

    public int getPort() {
        return mPort;
    }

    /**
     * 判断字符串是否ip格式
     * @param string
     * @return
     */
    private boolean isIP(String string) {
        if(string == null) {
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
        Matcher matcher = pattern.matcher(string);
        return matcher.matches();
    }

    public String getHostIP() {
        if(isIP(mHost)) {
            mHostIP = mHost;
        } else {
            try {
                mHostIP = InetAddress.getByName(mHost).getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
                return null;
            }
        }

        return mHostIP;
    }

    public boolean isHostIP() {
        return isIP(mHost);
    }


    public static void main(String[] args) {

        KUrl urlTest = null;
        urlTest = new KUrl("http://www.cnblogs.com:7890/shihaiming/p/6978517.html?v=&=world");
//        new KUrl("www.baidu.com");

        System.out.println(urlTest.mParamMap);
//-----------------------------------------------------------
//        String strTest = "www.cnblogs.com";
//        String[] strArray = strTest.split(":");
//
//        System.out.println("len="+strArray.length);
//        for(int i = 0; i < strArray.length; i++) {
//            System.out.println(strArray[i]);
//        }

    }
}
